package com.lemon.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.lemon.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

//@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录或登出请求直接放行
        if (("/employee/login".equals(request.getRequestURI()) || ("/employee/logout".equals(request.getRequestURI())))) {
            return true;
        }

        //判断是否登录
        Long userId = (Long) request.getSession().getAttribute("userInfo");
        if (userId != null) {
            return true;
        }
        //response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //response.setContentType("application/json;charset=UTF-8");
       /* response.getOutputStream().write(JSON.toJSONString(R.error("NOTLOGIN")).getBytes(StandardCharsets.UTF_8));*/
        response.getWriter().println(JSON.toJSONString(R.error("NOTLOGIN")));
        //response.sendRedirect("/backend/page/login/login.html");
        return false;
    }
}
